import { StoreKeys } from "@/common/enum";
import { getStorage, setStorage } from "@/common/util";
import { defineStore } from "pinia";

export interface ItemProp {
  id: number;
  title: string;
  checked: boolean;
}

interface titleProp {
  items: [ItemProp];
}

export const useList = defineStore(StoreKeys.list, {
  state: (): titleProp => {
    const str = getStorage(StoreKeys.list);
    const _items = str
      ? JSON.parse(str)
      : [
          {
            id: 1,
            title: "例如：六点起床背单词",
            checked: false,
          },
        ];
    return {
      items: _items,
    };
  },
  getters: {
    searchItem: ({ items }) => {
      const targets = (title: string) => items.filter((i) => i.title === title);
      return targets;
    },
  },
  actions: {
    setList(_title: string): void {
      this.items.push({
        id: this.items.length + 1,
        title: _title,
        checked: false,
      });
      setStorage(StoreKeys.list, JSON.stringify(this.items));
    },
    checkedItem(id: number): void {
      const _items = this.items.map((i) => {
        if (i.id === id) i.checked = !i.checked;
        return i;
      });
      setStorage(StoreKeys.list, JSON.stringify(_items));
    },
    deleteItem(id: number) {
      const targetIdx = this.items.findIndex((i) => i.id === id);
      if (targetIdx !== -1) {
        this.items.splice(targetIdx, 1);
        setStorage(StoreKeys.list, JSON.stringify(this.items));
      }
    },
  },
});
